﻿using Serilog.Context;
using SqlSugar;

namespace Net8.Project.Common.LogHelper
{
    /// <summary>
    /// 日志上下文扩展，支持 Serilog 日志属性作用域管理
    /// </summary>
    public class LogContextExtension : IDisposable
    {
        private readonly Stack<IDisposable> _scopeStack = new();

        /// <summary>
        /// 创建 LogContextExtension 实例
        /// </summary>
        public static LogContextExtension CreateInstance => new LogContextExtension();

        /// <summary>
        /// 日志来源属性名
        /// </summary>
        public static readonly string LogSource = "LogSource";

        /// <summary>
        /// AOP SQL 日志标识
        /// </summary>
        public static readonly string AopSql = "AopSql";

        /// <summary>
        /// 文件日志消息模板
        /// </summary>
        public static readonly string FileMessageTemplate =
            "{NewLine}Date：{Timestamp:yyyy-MM-dd HH:mm:ss.fff}{NewLine}LogLevel：{Level}{NewLine}Message：{Message}{NewLine}{Exception}" +
            new string('-', 100);

        /// <summary>
        /// 添加一个日志属性作用域到栈中
        /// </summary>
        /// <param name="scope">可释放的日志属性作用域</param>
        public void AddScope(IDisposable scope)
        {
            _scopeStack.Push(scope);
        }

        /// <summary>
        /// 为 SQL AOP 操作推送日志属性作用域
        /// </summary>
        /// <param name="db">ISqlSugarClient 实例</param>
        /// <returns>当前 LogContextExtension 实例（用于释放）</returns>
        public IDisposable SqlAopPushProperty(ISqlSugarClient db)
        {
            AddScope(LogContext.PushProperty(LogSource, AopSql));
            return this;
        }

        /// <summary>
        /// 释放所有日志属性作用域
        /// </summary>
        public void Dispose()
        {
            while (_scopeStack.Count > 0)
            {
                _scopeStack.Pop().Dispose();
            }
        }
    }
}
